package com.qjc.demo.train.half;

/**
 * @ClassName: HalfDemo
 * @Description: 二分查找法，在有序数组中找到某个数的位置
 * @Author: qjc
 * @Date: 2022/5/1 1:13 PM
 */
public class HalfDemo {

    public static int binarySearch(int[] nums, int t) {
        // 低位索引
        int low = 0;
        // 高位索引
        int high = nums.length - 1;
        // 中间索引
        int mid = 0;
        while (low <= high) {
            mid = (low + high) / 2;
            if (t == nums[mid]) {
                return mid;
            } else if (t < nums[mid]) {
                // 半数以内
                high = mid - 1;
            } else {
                // 半数以外
                low = mid + 1;
            }
        }
        return -1;

    }

    public static void main(String[] args) {
        int[] nums = {3, 12, 24, 31, 46, 48, 52, 66, 69, 79, 82};
        int i = binarySearch(nums, 52);
        System.err.println(i);
    }
}
